import { getCategoryList, getSubCategoryList } from '../../services/good/fetchCategoryList';

Page({
  data: {
    list: [],
    loading: false,
  },

  async init() {
    try {
      this.setData({ loading: true });
      const result = await getCategoryList();
      this.setData({
        list: result,
        loading: false,
      });
    } catch (error) {
      console.error('获取分类列表失败:', error);
      this.setData({ loading: false });
    }
  },

  async onChange(e) {
    const [activeIndex] = e.detail;
    const currentCategory = this.data.list[activeIndex];
    
    if (!currentCategory) {
      return;
    }

    try {
      // 如果当前一级分类还没有加载二级分类，则加载
      if (!currentCategory.children || currentCategory.children.length === 0) {
        const subCategories = await getSubCategoryList(currentCategory.id);
        
        // 更新当前一级分类的children
        const updatedList = [...this.data.list];
        updatedList[activeIndex].children = subCategories;
        
        this.setData({
          list: updatedList,
        });
      }
    } catch (error) {
      console.error('获取二级分类失败:', error);
      wx.showToast({
        title: '获取分类失败',
        icon: 'error',
        duration: 2000,
      });
    }
  },

  onShow() {
    this.getTabBar().init();
  },

  onCategorySelect(e) {
    // 当选择具体分类时，跳转到商品列表页
    const { item } = e.detail;
    console.log('选择的分类:', item);
    
    if (item && item.id) {
      wx.navigateTo({
        url: `/pages/goods/list/index?categoryId=${item.id}&categoryName=${encodeURIComponent(item.name || item.label || '商品分类')}`,
      });
    } else {
      wx.navigateTo({
        url: '/pages/goods/list/index',
      });
    }
  },

  onLoad() {
    this.init();
  },
});
